import React, { useState } from 'react';
import { AutoComplete } from 'antd';
import useDictionary from '@/hooks/useDictionary';

const { Option } = AutoComplete;

/**
 * @description  自动填充邮箱
 * @param dataSource 自定义的邮箱后缀数组，默认读取字典中的配置
 */
const MailAutoComplete = React.forwardRef(({ dataSource, ...rest }, ref) => {
    const [mailSuffixList, setMailSuffixList] = useState([]);
    // 字典数据
    const [gotoMailboxList = []] = useDictionary('gotoMailbox', {
        useCache: false,
        isAuth: false
    });

    const handleSearch = value => {
        let result;
        if (!value || value.indexOf('@') > 0) {
            result = [];
        } else {
            result = (dataSource || gotoMailboxList).map(
                item => `${value}${typeof item === 'object' ? item?.text : item}`
            );
        }
        setMailSuffixList(result);
    };
    return (
        <AutoComplete ref={ref} placeholder="请输入" {...rest} onSearch={handleSearch}>
            {mailSuffixList?.map(email => (
                <Option key={email}>{email}</Option>
            ))}
        </AutoComplete>
    );
});

export default MailAutoComplete;
